package com.lalilu.homework2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;

public class AnotherActivity extends AppCompatActivity {

    Bitmap temp = null;
    ConstraintLayout tempLayout = null;
    ValueAnimator animator = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another);
        this.setTitle("Second Activity");

        tempLayout = findViewById(R.id.background);
        findViewById(R.id.button2).setOnClickListener((view) -> {
            this.onBackPressed();
        });

        tempLayout.post(() -> {
            try {
                temp = BitmapFactory.decodeResource(getResources(), R.drawable._7018704_p0, getBitmapOption(8));

                animator = ValueAnimator.ofFloat(0.4f, 1f);
                animator.addUpdateListener(animation -> {
                    Float value = (Float) animation.getAnimatedValue();
                    int computedValue = Double.valueOf(50 * value).intValue();
                    if (computedValue == 0) computedValue = 1;
                    tempLayout.setBackground(new BitmapDrawable(FastBlur.doBlur(temp, computedValue, false)));
                });
                animator.setDuration(500);
                animator.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    @Override
    public void onBackPressed() {
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                finish();
            }
        });
        animator.setDuration(300);
        animator.reverse();
    }

    private BitmapFactory.Options getBitmapOption(int inSampleSize) {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }
}